package com.example.store.controller;

import com.example.store.common.JsonResult;
import com.example.store.entity.User;
import com.example.store.service.IUserService;
import com.example.store.service.impl.UserServiceImpl;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.javassist.expr.NewArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import static com.example.store.controller.BaseController.OK;

@RestController
@RequestMapping("user")
public class UserController extends BaseController{
    @Autowired
    private UserServiceImpl userService;

    @RequestMapping("reg")
    public JsonResult<Void> reg(User user) {
        userService.reg(user);

        return new JsonResult<Void>(OK);
    }
    @RequestMapping(value = "login")
    public JsonResult<User> login(String username, String password,HttpSession session){
        User data = userService.login(username,password);
        //登陆成功后，将用户的uid和username存入HttpSession中
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());
        /**
         * 或者在基类BaseController中添加方法来获取HttpSession
         * 中的uid和username，以便后续快速的获取这两个属性的值
         */
        System.out.println(getUsernameFromSession(session));
        System.out.println(getUidFromSession(session));
        return new JsonResult<User>(OK,data);
    }
    @RequestMapping("change_password")
    public JsonResult<Void> changePassword(String newPassword,String oldPassword,HttpSession httpSession){

        Integer uid = getUidFromSession(httpSession);

        String username = getUsernameFromSession(httpSession);

        userService.changePassword(uid,username,oldPassword,newPassword);

        return new JsonResult<Void>(OK);
    }
    @RequestMapping("get_by_uid")
    public JsonResult<User> getByUid(HttpSession httpSession){
    //从HtrpSession对象中获取uid
      Integer uid =  getUidFromSession(httpSession);
    //调用业务对象执行获取数据
        User data = userService.getByUid(uid);

        return new JsonResult<User>(OK,data);
    }
    @RequestMapping("change_Info")
    public JsonResult<Void> changeInfo(User user,HttpSession httpSession){
        //从HttpSession对象获取uid和username
        Integer uid = getUidFromSession(httpSession);
        String username = getUsernameFromSession(httpSession);
        //调用业务Service对象修改资料
        userService.changeInfo(uid,username,user);
        return new JsonResult<>(OK);
    }

}
